package com.gs.netty;

import com.gs.controller.IndexController;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.LoggerFactory;

/**
 * @ProjectName: springbootmybitstest
 * @Package: com.gs.netty
 * @Description: java类作用描述
 * @Author: Administrator
 * @CreateDate: 2018/7/3 14:59
 * @UpdateUser: Administrator
 * @UpdateDate: 2018/7/3 14:59
 * @UpdateRemark: The modified content
 * @Version: 1.0
 **/
public class TimeClientHandler  extends ChannelInboundHandlerAdapter {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TimeClientHandler.class);

    private int counter;
    private byte[] req;


    public TimeClientHandler(){
        req=("QUERY TIME ORDER"+System.getProperty("line.separator")).getBytes();


    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //将请求信息发送给服务端
        ByteBuf message=null;
        for (int i = 0; i < 100; i++) {
            message=Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    /**
     * @param ctx
     * @param msg
     * @throws Exception
     *当服务端返回应答消息时调用channelRead方法
     *
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //拿到的msg已经是解码成字符串之后的应答消息了，相比于之前的代码简洁明了很多。
        String body=(String) msg;
        System.out.println("Now is :"+body+" ;the counter is :" + ++counter);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //释放资源
        logger.error("Unexpected exception from downstream : "+cause.getMessage());
        ctx.close();
    }
}
